const { Service } = require("egg")
function parseTime(time, cFormat) {
  //console.log(time, cFormat)
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"
  let date
  if (typeof time === "object") {
    date = time
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), "/")
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value]
    }
    return value.toString().padStart(2, "0")
  })
  return time_str
}
class RoleService extends Service {
  async list(size, current, where) {
    const data = await this.app.mysql.select("egg_role", {
      where,
      orders: [
        ["id", "desc"],
        ["roleName", "desc"],
      ],
      offset: (size - 1) * current,
      limit: current,
    })
    const total = await this.app.mysql.count("egg_role", where)
    return { data, total }
  }
  async single(id) {
    const result = await this.app.mysql.get("egg_role", { id })
    return result
  }
  async create(role) {
    role.createTime = parseTime(role.createTime, "{y}-{m}-{d}_{h}:{i}:{s}")
    const result = await this.app.mysql.insert("egg_role", role)
    return result
  }
  async update(role) {
    if (role.updateTime) {
      role.updateTime = parseTime(role.updateTime, "{y}-{m}-{d}_{h}:{i}:{s}")
    }
    const result = await this.app.mysql.update("egg_role", role)
    return result
  }
  async destroy(id) {
    const result = await this.app.mysql.delete("egg_role", { id })
    return result
  }

  async getResouce() {
    const data = await this.app.mysql.select("egg_res")
    let rootMeun = []
    const map = {}
    data.map((item) => {
      item.children = []
      map[item.id] = item //把
      if (item.parentId === 0) {
        rootMeun.push(item)
      } else {
        map[item.parentId].children.push(item)
      }
    })
    return rootMeun
  }
  async setRes({ roleId, resouceIds }) {
    const { app } = this
    await app.mysql.query("DELETE FROM egg_role_res where roleId=?", [roleId])
    for (let i = 0; i < resouceIds.length; i++) {
      const resouceId = resouceIds[i]
      await app.mysql.insert("egg_role_res", {
        roleId: roleId,
        resId: resouceId,
      })
    }
  }

  async getUser() {
    const { app } = this
    const data = await app.mysql.select("egg_user")
    return data
  }
  async setUser({ roleId, userIds }) {
    const { app } = this
    await app.mysql.query("DELETE FROM egg_role_user where roleId=?", [roleId])
    for (let i = 0; i < userIds.length; i++) {
      const userId = userIds[i]
      await app.mysql.insert("egg_role_user", {
        roleId: roleId,
        userId: userId,
      })
    }
  }
}
module.exports = RoleService
